package durst.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import durst.action.CalendarContext;
import durst.data.Account;
import durst.data.Invite;

public class BucketFilter implements Filter {
	private static final Pattern pattern = Pattern.compile(".*/(\\d)+_([\\d\\w^_])+_(.+)");
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)resp;

		Account account = CalendarContext.getAccount(request, response);
		Matcher matcher = pattern.matcher(request.getRequestURI());
		
		if (matcher.matches() && !Integer.toString(account.getId()).equals(matcher.group(1)) && !matcher.group(2).equals("profile")) {
			for (Invite invite : account.getInvitedTo())
				if (Integer.toString(invite.getEvent().getId()).equals(matcher.group(2))) {
					chain.doFilter(req, resp);
					return;
				}
		}
		else if (matcher.matches()) {
			chain.doFilter(req, resp);
			return;
		}
		response.sendError(404);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
	
	@Override
	public void destroy() {
	}
}
